var config = require('../config/index.js')
var buildUrl = require('./buildUrl.js')
/**
 * 微信的的request
 */
module.exports = function request(options) {
  return new Promise(function(resolve, reject) {
    if (options.needLoading) {
      wx.showLoading()
    }
    let url = config.ApiRootUrl + options.url
    if (options.params) {
      url = buildUrl(url, options.params)
    }
    wx.request({
      url: url,
      data: options.data,
      method: options.method,
      header: {
        'Content-Type': 'application/json',
        'X-Token': wx.getStorageSync('token'),
        // 'X-Channel-Key': 'WXA_FUZIMIAO',
        // 'X-Channel-Key': 'WXA_LIT',
        // cookie: wx.getStorageSync('cookie'), //读取cookie
        // 'X-VILLAGE-ID': wx.getStorageSync('villageId'),
        // 'X-Version': '1.0.0'
      },
      success: function(res) {
        // 判断是否注册
        if(!wx.getStorageSync('isRegister')){
         //去授权注册页面
        }

        if(!wx.getStorageSync('isNglRegister')){
          //1 禁止通过          2 允许通过         3请尽快下载宁归来 页面 // 选择页面还没有 
          // 去选择能否进入首页的页面  只有2可以通过 进入首页  /pages/main/main 首页
         }

        // 00000 请求成功
        if (res.statusCode == 200) {
          
          if(res.data.code == '00000'){
            resolve(res.data.data || '')
          }else{
            // wx.showModal({
            //   title: '提示信息',
            //   content: '网络异常',
            //   showCancel: false
            // })
          }
        } else {
          reject(res)
        }
      },
      fail: function(err) {
        wx.showModal({
          title: '提示信息',
          content: '网络繁忙，请稍后再试',
          showCancel: false
        })
        reject(err)
      },
      complete: function(res) {
        
      }
    })
  })
}

function getCookie(cookiename, cookieStr) {
  var result
  var mycookie = cookieStr
  var start2 = mycookie.indexOf(cookiename + '=')
  if (start2 > -1) {
    var start = mycookie.indexOf('=', start2) + 1
    var end = mycookie.indexOf(';', start)

    if (end == -1) {
      end = mycookie.length
    }

    result = unescape(mycookie.substring(start, end))
  }

  return result
}